package com.cxs.drawpointdemo.slice;

import com.cxs.drawpointdemo.DrawAbility;
import com.cxs.drawpointdemo.GuessAbility;
import com.cxs.drawpointdemo.ResourceTable;
import com.cxs.drawpointdemo.constant.Common;
import com.cxs.drawpointdemo.data.Question;
import com.cxs.drawpointdemo.util.DeviceUtils;
import com.cxs.drawpointdemo.util.KvStoreUtils;
import com.cxs.drawpointdemo.util.ZSONUtils;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.window.service.WindowManager;
import ohos.data.distributed.common.*;
import ohos.data.distributed.user.SingleKvStore;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.system.DeviceInfo;

import java.util.List;


public class MainAbilitySlice extends AbilitySlice {

    static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00101, "MainAbility");
    private SingleKvStore kvStore;
    private boolean localIsReady;
    private boolean remoteIsReady;
    private int myChoose = Common.IS_DEFAULT;
    private Button btnDraw, btnGuess;
    private MyKvStoreObserver observer;

    /**
     * 监听分布式数据库的变化
     */
    class MyKvStoreObserver implements KvStoreObserver {
        @Override
        public void onChange(ChangeNotification changeNotification) {
            List<Entry> insertEntries = changeNotification.getInsertEntries();
            List<Entry> updateEntries = changeNotification.getUpdateEntries();
            insertEntries.forEach(entry -> changeNotifi(entry));
            updateEntries.forEach(entry -> changeNotifi(entry));
        }
    }

    private void changeNotifi(Entry entry) {
        String key = entry.getKey();
        switch (key) {
            case Common.REMOTE_CHOOSE_KEY:
                int remoteChoose = entry.getValue().getInt();
                getUITaskDispatcher().asyncDispatch(() -> {
                    // 更新按钮状态
                    setChooseButtonEnable(remoteChoose);
                });
                break;
            case Common.REMOTE_IS_READY_KEY:
                remoteIsReady = kvStore.getBoolean(Common.REMOTE_IS_READY_KEY);
                break;
        }
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        localIsReady = false;
        remoteIsReady = false;

        initDB();
        initComponent();
    }

    void initDB() {
        KvStoreUtils.setContext(getContext());
        kvStore = KvStoreUtils.getKvStore();
        observer = new MyKvStoreObserver();
        kvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_REMOTE, observer);
    }

    private void initComponent() {

        btnDraw = (Button) findComponentById(ResourceTable.Id_btn_choose_draw);
        btnDraw.setClickedListener(c -> {
            // 我来画
            myChoose = Common.IS_MY_DRAW;
            localIsReady = true;
            // 更新按钮背景
            btnDraw.setBackground(new ShapeElement(getContext(), ResourceTable.Graphic_background_button_select));
            btnGuess.setBackground(new ShapeElement(getContext(), ResourceTable.Graphic_background_button_enable));
            btnGuess.setEnabled(true);

            if (remoteIsReady) {
                kvStore.unSubscribe(observer);
                // 如果远程设备已准备，则进入游戏界面
                startFA("", DrawAbility.class.getName());
                startFA(DeviceUtils.getDeviceId(), GuessAbility.class.getName());
                return;
            }

            // 向远程设备发送消息
            kvStore.putInt(Common.REMOTE_CHOOSE_KEY, myChoose);
            kvStore.putBoolean(Common.REMOTE_IS_READY_KEY, true);
        });

        btnGuess = (Button) findComponentById(ResourceTable.Id_btn_choose_guess);
        btnGuess.setClickedListener(c -> {
            // 我来猜
            myChoose = Common.IS_MY_GUESS;
            localIsReady = true;

            if (remoteIsReady) {
                kvStore.unSubscribe(observer);
                // 如果远程设备已准备，则进入游戏界面
                startFA("", GuessAbility.class.getName());
                startFA(DeviceUtils.getDeviceId(), DrawAbility.class.getName());
                return;
            }

            btnDraw.setBackground(new ShapeElement(getContext(), ResourceTable.Graphic_background_button_enable));
            btnGuess.setBackground(new ShapeElement(getContext(), ResourceTable.Graphic_background_button_select));
            btnDraw.setEnabled(true);

            // 向远程设备发送消息
            kvStore.putInt(Common.REMOTE_CHOOSE_KEY, myChoose);
            kvStore.putBoolean(Common.REMOTE_IS_READY_KEY, true);
        });

    }

    private void setChooseButtonEnable(int remoteChoose) {
        ShapeElement disableElement = new ShapeElement(getContext(), ResourceTable.Graphic_background_button_disable);
        ShapeElement enableElement = new ShapeElement(getContext(), ResourceTable.Graphic_background_button_enable);
        if (remoteChoose == 1) {
            // 如果远程设备选择画
            btnDraw.setEnabled(false);
            btnGuess.setEnabled(true);
            btnDraw.setBackground(disableElement);
            btnGuess.setBackground(enableElement);
        } else if (remoteChoose == 2) {
            // 如果远程设备选择猜
            btnDraw.setEnabled(true);
            btnGuess.setEnabled(false);
            btnDraw.setBackground(enableElement);
            btnGuess.setBackground(disableElement);
        }
    }

    /**
     * 打开本地和远程设备的FA
     * @param deviceId
     * @param abilityName
     */
    private void startFA(String deviceId, String abilityName) {
        Intent intent = new Intent();
        Intent.OperationBuilder operationBuilder = new Intent.OperationBuilder()
                .withDeviceId(deviceId)
                .withBundleName(getBundleName())
                .withAbilityName(abilityName);
        if (!deviceId.equals("")) {
            operationBuilder.withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE);
        }
        intent.setOperation(operationBuilder.build());
        startAbility(intent);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            KvStoreUtils.getManager().closeKvStore(kvStore);
        } catch (KvStoreException e) {
            HiLog.warn(LABEL, "closeKvStore:" + e.getKvStoreErrorCode());
        }
    }
}
